#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import time
import subprocess
import platform

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

def run_prg(cmd):
    cmd_result = subprocess.Popen(cmd,
                                  shell=True,
                                  stderr=subprocess.STDOUT,
                                  stdout=subprocess.PIPE).communicate()[0]
    return cmd_result


def get_git_version(base_path):
    #  ver_last_commit = run_prg("git show --abbrev-commit --abbrev=8").split()
    ver_last_commit = run_prg("git show").split()
    current_ver_commit = ver_last_commit[1].decode("utf-8")
    version = current_ver_commit

    for lt in run_prg("git tag").split():
        v_show = run_prg("git show %s" % lt.decode("utf-8")).decode("utf-8")
        v_commit = v_show.split()
        v_commit = v_commit[v_commit.index("commit") + 1]
        if v_commit == current_ver_commit:
            version = lt.decode("utf-8")
            break
    else:
        version = current_ver_commit[0:8]

    diff = run_prg("git diff")
    if diff:
        print(bcolors.WARNING + "Warning:Git Repository Dirty!" + bcolors.ENDC)
        version = "%s_Dirty" % version
    return version


def get_prg_version(base_dir, argv):
    git_version = get_git_version(base_dir)
    v_data_time_str = time.strftime('%Y%m%d', time.localtime(time.time()))
    version = "".join(argv) + "_" + git_version + "_" + v_data_time_str
    print(bcolors.OKGREEN + version + bcolors.ENDC)
    return version


def get_main_dir():
    """Return the script directory - whether we're frozen or not."""
    return os.path.abspath(os.path.dirname(sys.argv[0]))


def get_system_info():
    sysinfo = ""
    for i in platform.uname()[0:3]:
        sysinfo += i + "@"
    sysinfo = sysinfo[0:-1]
    print(sysinfo)
    return sysinfo


def get_complier_info(complier_name="arm-gcc"):
    complier_info = ""
    cinfo = complier_name
    if complier_name == "arm-gcc":
        complier_info = str(run_prg("arm-none-eabi-gcc --version"))
    import re
    version = re.findall(r'\w{1,5}-\d{1,5}-\w{1,10}-\w{1,10}', complier_info)
    date = re.findall(r'\d{8}', complier_info)
    vnumber = re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}', complier_info)
    for v in (version, vnumber, date):
        if v:
            cinfo += "@" + v[0]
    print("%s" % cinfo)
    return cinfo


def gen_prg_header_file(base_dir, version_info):
    header_file_name = "/prg_version.h"
    f_version_h = open(base_dir + header_file_name, "w")
    f_version_h.writelines("//" + version_info["version"] + "\n")
    f_version_h.writelines("#ifndef _PRG_VERSION_H_\n")
    f_version_h.writelines("#define _PRG_VERSION_H_\n")
    f_version_h.writelines("#define PRG_VERSION \"%s\"\n" % version_info["version"])
    f_version_h.writelines("#define COMPILE_SYSINFO \"%s\"\n" % version_info["sysinfo"])
    f_version_h.writelines("#define COMPILER_INFO \"%s\"\n" % version_info["complier"])
    f_version_h.writelines("#endif\n")
    f_version_h.close()


def main(argv):
    # if "".join(argv) == "clean":
        # run_prg("git checkout prg_version.h")
        # return
    base_dir = get_main_dir()
    version_info = {"version": "", "sysinfo": "", "complier": ""}
    try:
        version_info["version"] = get_prg_version(base_dir, argv)
        version_info["sysinfo"] = get_system_info()
        version_info["complier"] = get_complier_info()
    except Exception as e:
        print("GenVersionException:%s" % e)
    gen_prg_header_file(base_dir, version_info)

if __name__ == '__main__':
    main(sys.argv[1:])
